package com.pzh.logistics.service.impl;

import com.pzh.logistics.common.constant.RoleConstant;
import com.pzh.logistics.exception.GlobalException;
import com.pzh.logistics.exception.ResultEnum;
import com.pzh.logistics.mbg.mapper.UserMapper;
import com.pzh.logistics.mbg.model.User;
import com.pzh.logistics.pojo.form.UserRegisterForm;
import com.pzh.logistics.service.UserInfoService;
import com.pzh.logistics.util.DozerUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional
    public int register(User user) {
        if (userMapper.findByUsername(user.getUsername()) != null){
            throw new GlobalException(ResultEnum.USERNAME_REPEAT);
        }
        user.setRole(RoleConstant.USER);
        return userMapper.insert(user);
    }

    @Override
    @Transactional
    public User updateInfo(UserRegisterForm form) {
        User user = new User();
        DozerUtil.transfor(form, user);
        form.setUsername(null);
        userMapper.updateByPrimaryKeySelective(user);
        return userMapper.selectByPrimaryKey(user.getUserId());
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findByUserId(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

}
